package com.test.nnooolwdeaer.activity_fragment_wooden.base_wooden;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.test.nnooolwdeaer.R;
import com.test.nnooolwdeaer.activity_fragment_wooden.fragment_wooden.RepayFragment_wooden;
import com.test.nnooolwdeaer.activity_fragment_wooden.info_wooden.FaceUploadActivity_Viet;
import com.test.nnooolwdeaer.activity_fragment_wooden.info_wooden.OcrUploadActivity_Viet;
import com.test.nnooolwdeaer.activity_fragment_wooden.info_wooden.SimInfoActivity_Viet;
import com.test.nnooolwdeaer.activity_fragment_wooden.loan_wooden.LoanMainActivity_wooden;
import com.test.nnooolwdeaer.activity_fragment_wooden.login_wooden.LoginPhoneNumActivity_wooden;
import com.test.nnooolwdeaer.bean_wooden.process_wooden.ProcessInfo_wooden;
import com.test.nnooolwdeaer.util_wooden.PermissionUtil_wooden;
import com.test.nnooolwdeaer.util_wooden.helper_wooden.ActivityHelper_wooden;
import com.test.nnooolwdeaer.util_wooden.helper_wooden.UserInfoHelper_wooden;
import com.test.nnooolwdeaer.util_wooden.http_wooden.HttpManager_wooden;
import com.test.nnooolwdeaer.util_wooden.http_wooden.HttpPresenter_wooden;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public abstract class BaseActivity_wooden extends AppCompatActivity implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    private Toast toast_wooden;

    private final int Code_Camera = 1;

    private Runnable cameraPermissionRunnable;

    //页面埋点
    public void recordPagePauseEvent_wooden(boolean isRepayOverdue) {
        //保存埋点
        String activityName = getClass().getSimpleName();
        if (!TextUtils.isEmpty(activityName)) {
            if (isRepayOverdue)
                HttpManager_wooden.getInstance_wooden().saveUserBuriedPointAndUpload((activityName + "_END").toUpperCase());
            else
                HttpManager_wooden.getInstance_wooden().saveUserBuriedPoint((activityName + "_END").toUpperCase());
        }
    }

    //处理用户流程状态
    public void onUserProcessResponse_wooden() {
        startActivityForSingleTop_wooden(LoanMainActivity_wooden.class);
    }

    public void showToastOnUiThread_wooden(String text) {
        runOnUiThread(() -> showToast_wooden(text));
    }

    @Override
    protected void onResume() {
        super.onResume();
        HttpPresenter_wooden.getInstance_wooden().setActivity_wooden(this);
        recordPageResumeEvent_wooden();
    }

    public void showToast_wooden(String text) {
        if (toast_wooden == null) toast_wooden = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        else toast_wooden.setText(text);
        toast_wooden.show();
    }

    public <T extends BaseActivity_wooden> void startActivityForSingleTop_wooden(Class<T> activityClass) {
        Intent intent = new Intent(this, activityClass);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity_wooden(activityClass);
        finish();
    }

    public void setBackBtn_wooden(View btnView) {
        btnView.setOnClickListener(view -> onBackPressed());
    }

    //页面埋点
    public void recordPageResumeEvent_wooden() {
        //保存埋点
        String activityName = getClass().getSimpleName();
        if (!TextUtils.isEmpty(activityName)) {
            HttpManager_wooden.getInstance_wooden().saveUserBuriedPoint((activityName + "_START").toUpperCase());
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (view != null) {
                if (ActivityHelper_wooden.canHideKeyboard_wooden(view, ev)) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager != null) {
                        ActivityHelper_wooden.hideKeyboard_wooden(this);
                        EditText editText = (EditText) view;
                        editText.clearFocus();
                    }
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
    }

    public <T extends BaseActivity_wooden> void startActivity_wooden(Class<T> activityClass) {
        startActivity(new Intent(this, activityClass));
    }

    @Override
    protected void onPause() {
        super.onPause();
        HttpPresenter_wooden.getInstance_wooden().setActivity_wooden(null);
        recordPagePauseEvent_wooden(this instanceof LoanMainActivity_wooden loanMainActivity
                && loanMainActivity.homeFragment_wooden != null
                && loanMainActivity.homeFragment_wooden instanceof RepayFragment_wooden repayFragment
                && repayFragment.isOverdue);
    }

    public void runAfterCameraPermission(Runnable runnable){
        if (PermissionUtil_wooden.checkLaunchPermissions_wooden(this, Manifest.permission.CAMERA)){
            runnable.run();
        }else {
            cameraPermissionRunnable = runnable;
            EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_camera), Code_Camera, Manifest.permission.CAMERA);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onRationaleAccepted(int requestCode) {}

    @Override
    public void onRationaleDenied(int requestCode) {}

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (requestCode == Code_Camera && cameraPermissionRunnable!=null) {
            cameraPermissionRunnable.run();
            cameraPermissionRunnable = null;
        }
    }

    //权限拒绝
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {}

    //处理越南的额外流程
    protected void handleVietnamExtProcess() {
        //3、流程接口增加配置：
        //"extStep": ["ocr_info", "liveness_info", "sim_info"],
        //"ocr_info": "SDK",
        ArrayList<String> extStep = ProcessInfo_wooden.getInstance_wooden().getExtStep();
        switch (extStep.get(0)) {
            case "ocr_info" -> startActivity_wooden(OcrUploadActivity_Viet.class);
            case "liveness_info" -> startActivity_wooden(FaceUploadActivity_Viet.class);
            case "sim_info" -> startActivity_wooden(SimInfoActivity_Viet.class);
        }
    }

    public void onDrop(){
        UserInfoHelper_wooden.getInstance_wooden().setMobile_wooden("");
        UserInfoHelper_wooden.getInstance_wooden().setToken_wooden("");
        UserInfoHelper_wooden.getInstance_wooden().setUserId_wooden("");
        startActivityForSingleTop_wooden(LoginPhoneNumActivity_wooden.class);
    }
}